<template>
  <el-row class="login-row" justify="center" align="middle">
    <el-col :span="8" :offset="0">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>登录</span>
            <el-button class="button" text>Operation button</el-button>
          </div>
        </template>
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="username">
            <el-input type="text" v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>
<script>
import { userLogin, roleGet } from "../api/user";
export default {
  data() {
    var validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号")); //验证失败
      } else {
        callback(); //验证通过
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: "富贵",
        password: "123",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          userLogin(this.ruleForm).then(async (res) => {
            // console.log(res);
            if (res.status == 200) {
              let { roleId } = res.data; //获取角色id
              let role = await roleGet(roleId); //同步等待roleGet执行完毕后，再执行后续逻辑
              console.log("角色信息", role);
              let info = { ...res.data, ...role.data }; //整合用户信息、角色信息
              this.$store.commit("user/initInfoMut", info); //存入状态机
              localStorage.setItem("vue-admin-2302", JSON.stringify(info)); //本地存储
              // localStorage['vue-admin-2302'] = res.data
              this.$router.push("/"); //路由跳转
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss">
.login-row {
  height: 100vh;
}
</style>
